/**设计图宽高 */
export let designSize = {
  w: 0,
  h: 0,
};
/**设计图宽高比 */
export let originAspectRatio = 0;

/**实际宽高 */
export const currentSize = {
  w: window.innerWidth,
  h: window.innerHeight,
};
/**实际宽高比 */
export let currentAspectRatio = 0;

/** 实际比设计的宽多少倍 */
export let scaleW = 0;
/** 实际比设计的高多少倍 */
export let scaleH = 0;

export let style = { w: 0, h: 0 };
/** 根元素的fontSize大小 */
export let rootFontSize = 0;

/**用于检测当前分辨率下的文字是否小于12px的问题 */
export const checkFont = (key: "w" | "h" = "w") => {
  const minFontSize = (designSize[key] * 12) / currentSize[key];
  console.warn(
    `此分辨率下,设计图的文字低于${Math.floor(
      minFontSize
    )}px的在这里都无法继续缩小，从而可能导致布局变形（浏览器不支持更小字体）。你可以尝试给这些文字增加scale([scaleW])`
  );
};

/**该函数需要配合css转rem的插件，比如postcss-px-to-viewport */
const screenFit = (width: number, height: number) => {
  /**设计图宽高 */
  designSize = {
    w: width,
    h: height,
  };
  /**设计图宽高比 */
  originAspectRatio = designSize.w / designSize.h;

  /**实际宽高比 */
  currentAspectRatio = currentSize.w / currentSize.h;

  /** 实际比设计的宽多少倍 */
  scaleW = currentSize.w / designSize.w;
  /** 实际比设计的高多少倍 */
  scaleH = currentSize.h / designSize.h;

  // 宽高比 比设计稿 大
  if (currentAspectRatio > originAspectRatio) {
    style.h = currentSize.h;
    style.w = (designSize.w * currentSize.h) / designSize.h;
    rootFontSize = (designSize.w / currentSize.w) * scaleH;
  }
  // 宽高比 比设计稿 小
  else if (currentAspectRatio < originAspectRatio) {
    style.h = (designSize.h * currentSize.w) / designSize.w;
    style.w = currentSize.w;
    rootFontSize = (designSize.w / currentSize.w) * scaleW;
  } else {
    style.h = designSize.h;
    style.w = designSize.w;
    rootFontSize = (designSize.w / currentSize.w) * 1;
  }

  checkFont();

  document.querySelector("html")!.style.fontSize = `${rootFontSize}vw`;
  const body = document.querySelector("body")!;
  const bodyStyle: Record<string, string> = {
    position: "fixed",
    top: "50%",
    left: "50%",
    transform: "translate3d(-50%, -50%, 0)",
    width: `${style.w}px`,
    height: `${style.h}px`,
    overflow: "hidden",
  };

  for (const key in bodyStyle) {
    const val = bodyStyle[key];
    body.style[key as any] = val;
  }
};

export default screenFit;
